package com.tataben.retrofit;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;

import okio.Buffer;
import retrofit2.Converter;

/**
 * JSON字符串的转换器(@Field, @FieldMap, @Header, @HeaderMap, @Path, @Query, @QueryMap)
 * Created by dlilang on 2017/11/7 0007.
 */
public class DLJsonRequestConverter<T> implements Converter<T, String> {
    private static final Charset UTF_8 = Charset.forName("UTF-8");

    private final Gson gson;
    private final TypeAdapter<T> adapter;

    DLJsonRequestConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    public String convert(T value) throws IOException {
        if (value instanceof String) return value.toString();
        Buffer buffer = new Buffer();
        Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
        JsonWriter jsonWriter = gson.newJsonWriter(writer);
        adapter.write(jsonWriter, value);
        jsonWriter.close();
        return buffer.readString(UTF_8);
    }
}